package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDto;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealGroup;
import com.itheima.service.CheckGroupService;
import com.itheima.service.CheckItemService;
import com.itheima.service.SetmealGroupService;
import com.itheima.service.SetmealService;
import com.itheima.support.PageResult;
import com.itheima.support.QueryPageBean;
import com.itheima.support.SysConst;
import com.itheima.utils.FileUtils;
import com.itheima.utils.RedisUtil;
import com.itheima.vo.CheckGroupVO;
import com.itheima.vo.SetmealVO;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Resource
    private SetmealGroupService setmealGroupService;

   @Resource
   private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private CheckGroupService checkGroupService;

    @Resource
    private CheckItemService checkItemService;


    @Override
    public boolean deleteById(Long id) {
        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setDeleteFlag(1);
        return this.updateById(setmeal);
    }

    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> setmeals = (List<Setmeal>) redisTemplate.opsForValue().get("setmeal:findAll");
        if (setmeals==null){
            QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("delete_flag",0);
            List<Setmeal> list = this.list(queryWrapper);
            redisTemplate.opsForValue().set("setmeal:findAll",list);
        }
       return setmeals;
    }

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        //pageParam 分页参数
        IPage<Setmeal> pageParam = new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag",0);//过滤出有效数据
        if(queryPageBean.getQueryString() != null && "".equals(queryPageBean.getQueryString().trim()) == false){//判断前端页面传过来的搜索关键字是否为空
            //where delete_flag = 0
            //and (code like '' or name like '')
            queryWrapper.and(wrapper -> {
                wrapper.like("code",queryPageBean.getQueryString()).or()
                        .like("name",queryPageBean.getQueryString()).or()
                        .like("help_code",queryPageBean.getQueryString());
            });
        }
        //分页查询
        this.page(pageParam,queryWrapper);
        //分页的返回结果
        return new PageResult(pageParam.getTotal(),pageParam.getRecords());
    }

    @Override
    public boolean save(SetmealDto setmealDto) {
        //1.保存套餐
        this.saveOrUpdate(setmealDto.getSetmeal());
        //从file:set集合移除我们的图片
        if(setmealDto.getSetmeal().getImg() != null){
//            redisTemplate.opsForSet().remove("file:allset",setmealDto.getSetmeal().getImg());
            RedisUtil.removeSetMember(SysConst.SETMEAL_ALL_SET,setmealDto.getSetmeal().getImg());
        }
        //2.删除关系表数据
        setmealGroupService.deleteBySetmealId(setmealDto.getSetmeal().getId());
        //3.维护关系数据
        List<SetmealGroup> groups = new ArrayList<>();
        for(Long groupId : setmealDto.getGroupIds()){
            SetmealGroup setmealGroup = new SetmealGroup();
            setmealGroup.setSetmealId(setmealDto.getSetmeal().getId());
            setmealGroup.setGroupId(groupId);
            groups.add(setmealGroup);
        }
        //insert into table(id,name) values(),(),()
        setmealGroupService.saveBatch(groups);
        return true;
    }

    @Override
    public void clearOssObject() {
        //1.取出file:allset集合元素
//        Set<Object> allSet = redisTemplate.opsForSet().members("file:allset");
        Set allSet = RedisUtil.getMembersOfSet(SysConst.SETMEAL_ALL_SET);
        if(allSet != null){
            for(Object path : allSet){
                String fileKey = "file:" + path;
//                if(redisTemplate.hasKey(fileKey) == false){
                if(RedisUtil.hasKey(fileKey)){
                    //从oss删除
                    FileUtils.delete((String)path);
                    //从file:allset移除出去
//                    redisTemplate.opsForSet().remove("file:allset",path);
                    RedisUtil.removeSetMember(SysConst.SETMEAL_ALL_SET,path);
                }
            }
        }
    }

    @Override
    public SetmealVO findSetmealDetail(Long setmealId) {
        //1.查询套餐基本信息
//        SetmealVO setmealVO = new SetmealVO();
//        Setmeal setmeal = this.getById(setmealId);
//        BeanUtils.copyProperties(setmeal,setmealVO);
       SetmealVO setmealVO = RedisUtil.get("setmeal:" + setmealId);
        if (setmealVO==null){
          //数据库查询
           setmealVO = this.baseMapper.findById(setmealId);
          //2.通过套餐查询检查组列表
          List<CheckGroupVO> groups = checkGroupService.findBySetmealId(setmealId);
          setmealVO.setCheckGroups(groups);
          //3.通过检查组查询检查项列表
          if(groups != null){
              for(CheckGroupVO group : groups){
                  group.setCheckItems(checkItemService.findByGroupId(group.getId()));
              }
          }
          //redis缓存
          RedisUtil.set("setmeal:"+setmealId,setmealVO);
      }

        return setmealVO ;
    }

}
